﻿Imports WiremetModel.Entities.Tracking
Imports WiremetModel.Specification.GeneralSpecifications

Public Class DrutyBrowserForm

    Private unitOfWork As UnitOfWork


    Public Sub New()

        InitializeComponent()
        unitOfWork = New UnitOfWork()

    End Sub

    Private Sub DrutyBrowserForm_Activated(sender As System.Object, e As System.EventArgs) Handles MyBase.Activated
        tb_DrutId.SelectAll()
    End Sub

    Private Sub DrutyBrowserForm_FormClosed(sender As Object, e As FormClosedEventArgs) Handles Me.FormClosed
        unitOfWork.Dispose()
    End Sub


    Private Sub tb_DrutId_KeyPress(sender As Object, e As KeyPressEventArgs) Handles tb_DrutId.KeyPress
        If e.KeyChar = Microsoft.VisualBasic.ChrW(Keys.Return) Then

            Try
                Dim drutId As Integer

                If (Not Int32.TryParse(tb_DrutId.Text.Trim(), drutId)) OrElse drutId <= 0 Then
                    Throw New ArgumentException("Proszę podaj poprawny numer drutu.")
                End If

                Dim drut As Drut = GetDrut(drutId)
                Dim pozycjaSchematuId As Integer = drut.PozycjaSchematu.Id
                Dim schemat = drut.PozycjaSchematu.Schemat
                Dim pozycjaSchematuIdList As IList(Of Integer) = schemat.PozycjeSchematu.Values.Where(Function(x) x.Id >= pozycjaSchematuId).Select(Function(x) x.Id).OrderBy(Function(x) x).ToList()
                If pozycjaSchematuIdList.Count >= 2 Then
                    pozycjaSchematuId = pozycjaSchematuIdList(1)
                End If

                Dim pozycjaSchematu As New clsInhTrPozycjeSchematu(pozycjaSchematuId, New clsDataBase(VAR_CONNECTION_PARAMETERS, VAR_ERROR_HANDLER))
                Dim operacja2Form As New frmOperacja2(New Collection(Of clsInhTrPozycjeSchematu)({pozycjaSchematu}), 0)

                operacja2Form.MdiParent = MdiParent
                operacja2Form.Show()
                tb_DrutId.SelectAll()

            Catch ex As Exception
                MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
            End Try

        End If
    End Sub


    Private Function GetDrut(ByVal drutId As Integer) As Drut

        Dim drutRepository As New Repository(Of Drut)(unitOfWork)
        Dim drutIdSpecification As New IdSpecification(Of Drut)(drutId)
        Dim drut = drutRepository.GetEntityMatching(drutIdSpecification)

        If IsNothing(drut) Then
            Throw New Exception("Nie znaleziono drutu o podanym numerze.")
        End If

        Return drut

    End Function




End Class